import os

from django.conf import settings
from django.forms import model_to_dict
from django.shortcuts import render
from rest_framework import status
from rest_framework.filters import OrderingFilter
from rest_framework.generics import CreateAPIView, ListAPIView, UpdateAPIView, DestroyAPIView, RetrieveAPIView, \
    RetrieveDestroyAPIView, ListCreateAPIView
from rest_framework.response import Response

from articles.models import Article, Comment
from articles.pagenition import LargeResultsSetPagination
from articles.serializers import ArticleCreateSerializer, ArticleListSerializer, ArticleUpdateSerializer, \
    AllArticleSerializer, ArticleUpdateSomeSerializer, ArticleCommentSerializer, AddCommentSerializer, \
    DeleteCommentSerializer
from renameImg import imgpath
from rest_framework.views import APIView

from users.serializers import UserDetailModelSerializer


# Create your views here.

class ArticleAPIView(CreateAPIView):
    queryset = Article.objects.filter(is_active=True).all()
    serializer_class = ArticleCreateSerializer


class UploadImgView(APIView):
    # 上传头像
    def post(self, request):
        # 获取文件对象
        imgs = ""
        filelist = request.data.getlist("file")
        # file.file  上传文件的字节流
        # file.name  上传文件的名字

        # 拼接路径
        # static_path : 该路径前后不能有斜杠  对拼接有影响
        # 将静态资源文件夹拼接到项目根目录
        if not filelist:
            return
        for file in filelist:
            name = imgpath()
            end_fix = file.name.split(".")[-1]
            if end_fix not in ['jpg', 'png', 'jpeg', 'webp']:
                return Response({"msg": "图片格式不正确"})
            imgPath = os.path.join(settings.STATIC_PATH, 'articles/2024/' + name + "." + end_fix)

            # 保存图片
            # wb  以二进制形式写入
            with open(imgPath, "wb") as f:
                # 写入字节流
                f.write(file.file.read())
            imgs = imgs + 'articles/2024/' + name + "." + end_fix + ","

        # 返回响应
        data = {
            "code": 200,
            'msg': "上传图片成功",
            'imgPath': imgs[:-1]
        }
        return Response(data)


class ArticleListView(ListAPIView):
    serializer_class = ArticleListSerializer
    filter_backends = [OrderingFilter, ]
    ordering_fields = ['create_time', 'add_love']

    def get_queryset(self):
        uid = self.kwargs.get('user_id')
        return Article.objects.filter(user_id=uid, is_active=True).all()


class ArticleUpdateSerializer(UpdateAPIView):
    serializer_class = ArticleUpdateSerializer
    queryset = Article.objects.all()


class AllArticleListView(ListAPIView):
    serializer_class = AllArticleSerializer
    pagination_class = LargeResultsSetPagination
    filter_backends = [OrderingFilter, ]
    ordering_fields = ['create_time', 'add_love']
    queryset = Article.objects.filter(is_active=True).all()


# 删除某个文章
class ArticleDeleteView(DestroyAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleListSerializer


class AddSomeArticleView(UpdateAPIView):
    serializer_class = ArticleUpdateSomeSerializer
    queryset = Article.objects.all()


# 查询莫个文章的评论
class CommentView(APIView):
    def get(self, request, article_id):
        try:
            comments = Comment.objects.filter(article_id=article_id, is_active=True, level=0).all()
            comments_dict = []
            for comment in comments:
                parent_dict = model_to_dict(comment)
                parent_dict['create_time'] = comment.create_time.strftime('%Y-%m-%d %H:%M:%S')
                parent_dict['user'] = UserDetailModelSerializer(instance=comment.user).data
                children = Comment.objects.filter(comment_id=comment.id, is_active=True, level=1).all()
                child_list = []
                for child in children:
                    child_dict = model_to_dict(child)
                    child_dict['create_time'] = child.create_time.strftime('%Y-%m-%d %H:%M:%S')
                    child_dict['user'] = UserDetailModelSerializer(instance=child.user).data
                    child_list.append(child_dict)
                parent_dict['child_comment'] = child_list
                comments_dict.append(parent_dict)
            return Response(comments_dict, status=status.HTTP_200_OK)
        except:
            return Response({"msg": "查询失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 新增评论
class AddCommentView(CreateAPIView):
    serializer_class = AddCommentSerializer
    queryset = Comment.objects.filter(is_active=True)


# 删除评论
class DeleteCommentView(APIView):
    def delete(self, request):
        try:
            id = request.query_params.get('id')
            comment = Comment.objects.filter(id=id, is_active=True).first()
            comment.delete()
            return Response({"code": 200, "msg": "删除成功"})
        except:
            return Response({"code": 500, "msg": "删除失败"})
